package com.spider.spiderorderadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spider.spiderorderadmin.entity.dto.DataDictionaryDTO;
import com.spider.spiderorderadmin.entity.model.DataDictionary;
import com.spider.spiderorderadmin.entity.model.DataDictionaryDesc;
import com.spider.spiderorderadmin.entity.param.DataDictionaryQueryParam;
import com.spider.spiderorderadmin.exception.BusinessException;
import com.spider.spiderorderadmin.exception.ExceptionDef;
import com.spider.spiderorderadmin.mapper.DataDictionaryMapper;
import com.spider.spiderorderadmin.service.DataDictionaryService;
import com.spider.spiderorderadmin.mapper.DataDictionaryDescMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2020/12/1 17:48
 */

@Service
public class DataDictionaryServiceImpl extends ServiceImpl<DataDictionaryMapper, DataDictionary>
        implements DataDictionaryService {

    @Autowired
    private DataDictionaryDescMapper dataDictionaryDescMapper;

    @Override
    public Page<DataDictionary> selectPage(DataDictionaryQueryParam queryParam) {
        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(queryParam.getKeyName()), DataDictionary::getKeyName, queryParam.getKeyName());
        queryWrapper.like(StringUtils.hasText(queryParam.getKeyCode()), DataDictionary::getKeyCode, queryParam.getKeyCode());
        queryWrapper.orderByDesc(DataDictionary::getCreateTime);
        return this.baseMapper.selectPage(queryParam.buildPage(), queryWrapper);
    }


    @Override
    public DataDictionaryDTO findById(Long id) {

        DataDictionary dictionary = this.baseMapper.selectById(id);
        if (dictionary == null) {
            throw new BusinessException(ExceptionDef.ERROR_DATA_NOT_EXIST);
        }
        List<DataDictionaryDesc> dictionaryDescList = dataDictionaryDescMapper.selectList(buildDictDescQueryWrapper(id));

        DataDictionaryDTO result = new DataDictionaryDTO();
        result.setId(dictionary.getId());
        result.setKeyName(dictionary.getKeyName());
        result.setRemark(dictionary.getRemark());
        result.setKeyCode(dictionary.getKeyCode());
        result.setDictionaryDescList(dictionaryDescList);

        return result;
    }


    @Override
    public DataDictionaryDTO saveDataDictionary(DataDictionaryDTO dictionaryDto) {

        DataDictionary dataDictionary = new DataDictionary();
        dataDictionary.setKeyName(dictionaryDto.getKeyName());
        dataDictionary.setRemark(dictionaryDto.getRemark());
        dataDictionary.setKeyCode(dictionaryDto.getKeyCode());

        this.baseMapper.insert(dataDictionary);

        List<DataDictionaryDesc> dictionaryDescList = dictionaryDto.getDictionaryDescList();
        if (!CollectionUtils.isEmpty(dictionaryDescList)) {
            for (DataDictionaryDesc desc : dictionaryDescList) {
                DataDictionaryDesc dictDesc = new DataDictionaryDesc();
                dictDesc.setDictionaryId(dataDictionary.getId());
                dictDesc.setValueCode(desc.getValueCode());
                dictDesc.setValueEn(desc.getValueEn());
                dictDesc.setValueCn(desc.getValueCn());
                dataDictionaryDescMapper.insert(dictDesc);
            }
        }
        return dictionaryDto;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DataDictionaryDTO updateDataDictionary(DataDictionaryDTO dictionaryDto) {

        Long dictionaryId = dictionaryDto.getId();
        DataDictionary dictionary = this.baseMapper.selectById(dictionaryId);
        if (dictionary == null) {
            throw new BusinessException(ExceptionDef.ERROR_DATA_NOT_EXIST);
        }
        dictionary.setKeyName(dictionaryDto.getKeyName());
        dictionary.setRemark(dictionaryDto.getRemark());
        this.baseMapper.updateById(dictionary);

        // 先删除字典详情表的关联数据
        dataDictionaryDescMapper.delete(buildDictDescQueryWrapper(dictionaryId));

        // 再重新新增字典详情表数据
        List<DataDictionaryDesc> dictionaryDescList = dictionaryDto.getDictionaryDescList();
        if (!CollectionUtils.isEmpty(dictionaryDescList)) {
            for (DataDictionaryDesc desc : dictionaryDescList) {
                DataDictionaryDesc dictDesc = new DataDictionaryDesc();
                dictDesc.setDictionaryId(dictionaryId);
                dictDesc.setValueCode(desc.getValueCode());
                dictDesc.setValueEn(desc.getValueEn());
                dictDesc.setValueCn(desc.getValueCn());
                dataDictionaryDescMapper.insert(dictDesc);
            }
        }

        return dictionaryDto;
    }

    @Override
    public Boolean deleteById(String ids) {
        if (ids == null) {
            return true;
        }
        List<Long> idList = new ArrayList<>();
        if (ids.contains(",")) {
            String[] splitArray = ids.split(",");
            for (String str : splitArray) {
                idList.add(Long.parseLong(str));
            }
        } else {
            idList.add(Long.parseLong(ids));
        }
        // 先删除字典详情表的数据
        dataDictionaryDescMapper.delete(buildDictDescInQueryWrapper(idList));
        this.baseMapper.deleteBatchIds(idList);
        return true;
    }

    @Override
    public DataDictionaryDesc createDictDesc(DataDictionaryDesc dictionaryDesc) {
        DataDictionary dictionary = this.baseMapper.selectById(dictionaryDesc.getDictionaryId());
        if (dictionary == null) {
            throw new BusinessException(ExceptionDef.ERROR_DATA_NOT_EXIST);
        }
        dataDictionaryDescMapper.insert(dictionaryDesc);
        return dictionaryDesc;
    }

    @Override
    public DataDictionaryDesc updateDictDesc(DataDictionaryDesc dictionaryDesc) {
        DataDictionaryDesc dataDictionaryDesc = dataDictionaryDescMapper.selectById(dictionaryDesc.getId());
        dataDictionaryDesc.setValueCn(dictionaryDesc.getValueCn());
        dataDictionaryDesc.setValueEn(dictionaryDesc.getValueEn());
        dataDictionaryDescMapper.updateById(dataDictionaryDesc);
        return dataDictionaryDesc;
    }

    @Override
    public Boolean deleteDictDesc(Long id) {
        dataDictionaryDescMapper.deleteById(id);
        return true;
    }

    /**
     * 构建根据字典主表ID查询字典详情表的LambdaQueryWrapper
     */
    private LambdaQueryWrapper<DataDictionaryDesc> buildDictDescQueryWrapper(Long dictionaryId) {
        LambdaQueryWrapper<DataDictionaryDesc> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataDictionaryDesc::getDictionaryId, dictionaryId);
        queryWrapper.orderByDesc(DataDictionaryDesc::getCreateTime);
        return queryWrapper;
    }

    private LambdaQueryWrapper<DataDictionaryDesc> buildDictDescInQueryWrapper(List<Long> dictionaryIds) {
        LambdaQueryWrapper<DataDictionaryDesc> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DataDictionaryDesc::getDictionaryId, dictionaryIds);
        queryWrapper.orderByDesc(DataDictionaryDesc::getCreateTime);
        return queryWrapper;
    }


}
